package cn.ehangsoft.tinymce_upload.controller;

import cn.ehangsoft.tinymce_upload.MyFileNotFoundException;
import cn.ehangsoft.tinymce_upload.UploadResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;


@Controller
@RequestMapping("/file")
public class FileUploadController {
    static Logger logger = LoggerFactory.getLogger("fileupload");
    final static String uploafBasePath = "/Users/user/projects/yuanian/tinymce-upload/upload-temp/";
    @GetMapping("/upload")
    public String upload() {
        return "index";
    }
    @PostMapping("/upload")
    @CrossOrigin(origins = "*")
    public UploadResponse upload(@RequestParam("file") MultipartFile file) {
        UploadResponse response = new UploadResponse();
        if (file.isEmpty()) {
            logger.info("上传失败，请选择文件。");
            response.setMessage("上传失败，请选择文件.");
            response.setSuccess(false);
            return response;
        }

        String fileName = file.getOriginalFilename();
        String filePath = uploafBasePath;

        File dest = new File(filePath + fileName);
        logger.info("文件保存路径:{}",dest.getAbsolutePath());
        File parentPath = new File(filePath);
        try {
            if(!parentPath.exists()){
                parentPath.mkdirs();
            }
            file.transferTo(dest);
            logger.info("上传成功。");
            response.setMessage("上传成功.");
            response.setSuccess(true);
            response.setFileUrl(fileName);
            return response;
        } catch (IOException e) {
            logger.error("上传失败。",e);
        }
        response.setMessage("上传失败，请选择文件.");
        response.setSuccess(false);
        return response;
    }

    @GetMapping("/downloadFile/{fileName:.+}")
    @CrossOrigin(origins = "*")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
        logger.info("访问文件：{}.",fileName);
        // Load file as Resource
        Resource resource = loadFileAsResource(fileName);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("无法检测文件类型.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }
        logger.info("文件类型:{}",contentType);
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    private Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = Paths.get(uploafBasePath).toAbsolutePath().normalize().resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new MyFileNotFoundException("File not found " + fileName);
            }
        } catch (MalformedURLException ex) {
            throw new MyFileNotFoundException("File not found " + fileName, ex);
        }
    }
}
